package com.masterclient.app.modules.shop;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.alibaba.android.vlayout.layout.StaggeredGridLayoutHelper;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.managerlibrary.router.AroutePath;
import com.eoner.managerlibrary.user.UserDataManager;
import com.masterclient.app.BaseActivity;
import com.masterclient.app.R;
import com.masterclient.app.modules.search.beans.SearchProductsBean;
import com.masterclient.app.modules.shop.adapter.ProductsLayoutAdapter;
import com.masterclient.app.modules.shop.contract.SearchGoodsContract;
import com.masterclient.app.modules.shop.contract.SearchGoodsPresenter;
import com.masterclient.app.widget.TitlebarView;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnEditorAction;

/**
 * @auther hjian
 * @date 2020/4/15.
 */
@Route(path = AroutePath.STORE_SEARCH_ACTIVITY)
public class StoreSearchActivity extends BaseActivity<SearchGoodsPresenter> implements SearchGoodsContract.View {

    @BindView(R.id.store_search_titlebar)
    TitlebarView storeSearchTitlebar;
    @BindView(R.id.store_search_edit)
    EditText storeSearchEdit;
    @BindView(R.id.store_search_clear)
    FrameLayout storeSearchClear;
    @BindView(R.id.store_search_back)
    TextView storeSearchBack;
    @BindView(R.id.store_search_framelayout)
    RelativeLayout storeSearchFramelayout;
    @BindView(R.id.store_sequence_sale)
    TextView storeSequenceSale;
    @BindView(R.id.store_sequence_commission)
    TextView storeSequenceCommission;
    @BindView(R.id.store_sequence_new)
    TextView storeSequenceNew;
    @BindView(R.id.store_sequence_price)
    TextView storeSequencePrice;
    @BindView(R.id.store_sequence_priceicon)
    ImageView storeSequencePriceicon;
    @BindView(R.id.store_sequence_pricell)
    LinearLayout storeSequencePricell;
    @BindView(R.id.store_sequence_switchicon)
    ImageView storeSequenceSwitchicon;
    @BindView(R.id.store_sequence_switch)
    FrameLayout storeSequenceSwitch;
    @BindView(R.id.store_search_recyclerView)
    RecyclerView storeSearchRecyclerView;
    @BindView(R.id.store_search_refresh)
    SmartRefreshLayout storeSearchRefresh;
    @BindView(R.id.iv_back_top)
    ImageView ivBackTop;
    @BindView(R.id.empty_title)
    TextView emptyTitle;
    @BindView(R.id.empty_root)
    LinearLayout emptyRoot;
    @BindView(R.id.store_search_sequencelayout)
    RelativeLayout storeSearchSequencelayout;

    @Autowired(name = "store_id")
    String storeId;
    @Autowired(name = "isSearch")
    boolean isSearch;
    @Autowired(name = "tag")
    String tag;
    @Autowired(name = "title")
    String title;

    private VirtualLayoutManager manager;
    private ProductsLayoutAdapter recyclerAdapter;
    private DelegateAdapter delegateAdapter;
    private List<DelegateAdapter.Adapter> adapters;
    private int page;
    private boolean isStaggered;
    private String sequenceName;
    private int scrollY;
    private String keyword;
    private List<LayoutHelper> layoutHelpers;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store_search);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);


        page = 1;
        scrollY = 0;
        sequenceName = "hot";
        isStaggered = true;
        adapters = new LinkedList<>();
        keyword = "";

        storeSequenceCommission.setVisibility(TextUtils.isEmpty(UserDataManager.getInstance().getRoleLevel()) || Integer.parseInt(UserDataManager.getInstance().getRoleLevel()) < 10 ? View.GONE : View.VISIBLE);


        emptyTitle.setText("没有找到您要的商品");
        storeSearchTitlebar.setVisibility(isSearch ? View.GONE : View.VISIBLE);
        storeSearchFramelayout.setVisibility(isSearch ? View.VISIBLE : View.GONE);

        storeSearchTitlebar.setOnViewClick(new TitlebarView.onViewClick() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {

            }
        });

        storeSearchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                storeSearchClear.setVisibility(charSequence.toString().length() > 0 ? View.VISIBLE : View.INVISIBLE);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        storeSearchRefresh.setEnableLoadMoreWhenContentNotFull(false);
        storeSearchRefresh.setEnableFooterFollowWhenNoMoreData(true);
        storeSearchRefresh.setRefreshHeader(new MaterialHeader(getActivity()));
        storeSearchRefresh.setRefreshFooter(new ClassicsFooter(getActivity()));
        storeSearchRefresh.setOnMultiPurposeListener(new SimpleMultiPurposeListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                if (TextUtils.isEmpty(keyword)) {
                    storeSearchRefresh.finishRefresh();
                    return;
                }
                page = 1;
                scrollY = 0;

                storeSearchRefresh.setNoMoreData(false);
                searchGoods();
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                searchGoods();
            }
        });

        manager = new VirtualLayoutManager(this);
        storeSearchRecyclerView.setLayoutManager(manager);
        storeSearchRecyclerView.setItemViewCacheSize(20);
        storeSearchRecyclerView.setItemAnimator(null);

        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        for (int i = 0; i < 2; i++) {
            viewPool.setMaxRecycledViews(i + 5, 20);
        }
        storeSearchRecyclerView.setRecycledViewPool(viewPool);
        delegateAdapter = new DelegateAdapter(manager, true);


        LinearLayoutHelper linearLayoutProducts = new LinearLayoutHelper();
        linearLayoutProducts.setMargin(ScreenUtils.dp2px(16), ScreenUtils.dp2px(12)
                , ScreenUtils.dp2px(16), ScreenUtils.dp2px(10));
        linearLayoutProducts.setDividerHeight(ScreenUtils.dp2px(12));

        StaggeredGridLayoutHelper staggeredLayoutProducts = new StaggeredGridLayoutHelper(2);
        staggeredLayoutProducts.setHGap(ScreenUtils.dp2px(9));
        staggeredLayoutProducts.setVGap(ScreenUtils.dp2px(9));
        staggeredLayoutProducts.setMargin(ScreenUtils.dp2px(16), ScreenUtils.dp2px(12)
                , ScreenUtils.dp2px(16), ScreenUtils.dp2px(10));

        layoutHelpers = new ArrayList<>();
        layoutHelpers.add(staggeredLayoutProducts);
        layoutHelpers.add(linearLayoutProducts);

        recyclerAdapter = new ProductsLayoutAdapter(this, layoutHelpers, null, new ArrayList<>());
        recyclerAdapter.setStrings("店铺");
        adapters.add(recyclerAdapter);
        delegateAdapter.setAdapters(adapters);
        storeSearchRecyclerView.setAdapter(delegateAdapter);

        storeSearchRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                scrollY += dy;
                ivBackTop.setVisibility(scrollY > ScreenUtils.getScreenHeight() ? View.VISIBLE : View.GONE);
            }
        });

        if (!isSearch) {
            storeSearchTitlebar.setTitle(title);
            searchGoods();
        }else {
            tag = "";
            storeSearchEdit.postDelayed(()-> showSoftInput(storeSearchEdit),200);
        }

    }

    @OnClick({R.id.store_search_clear, R.id.store_search_back, R.id.store_sequence_sale, R.id.store_sequence_commission,
            R.id.store_sequence_new, R.id.store_sequence_pricell, R.id.store_sequence_switch, R.id.iv_back_top})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.store_search_clear:
                storeSearchEdit.getText().clear();
                break;
            case R.id.store_search_back:
                finish();
                break;
            case R.id.store_sequence_sale:
                setSequence("hot");
                break;
            case R.id.store_sequence_commission:
                setSequence("commission");
                break;
            case R.id.store_sequence_new:
                setSequence("new");
                break;
            case R.id.store_sequence_pricell:
                setSequence(sequenceName.equals("price_asc") ? "price_desc" : "price_asc");
                break;
            case R.id.store_sequence_switch:
                isStaggered = !isStaggered;
                storeSequenceSwitchicon.setImageResource(isStaggered ? R.mipmap.store_switch_grid : R.mipmap.store_switch_list);
                recyclerAdapter.setItemType(isStaggered);
                delegateAdapter.setAdapters(adapters);
                storeSearchRefresh.closeHeaderOrFooter();
                ivBackTop.setVisibility(View.GONE);
                storeSearchRecyclerView.scrollToPosition(0);
                scrollY = 0;

               break;
            case R.id.iv_back_top:
                scrollY = 0;
                ivBackTop.setVisibility(View.GONE);
                storeSearchRefresh.closeHeaderOrFooter();
                storeSearchRecyclerView.scrollToPosition(0);
                break;
        }
    }

    @OnEditorAction(R.id.store_search_edit)
    boolean onEditSearch(TextView tv, int imeAction, KeyEvent event) {
        if (imeAction == EditorInfo.IME_ACTION_SEARCH) {
            keyword = tv.getText().toString().trim();
            ((InputMethodManager) tv.getContext().getSystemService(
                    Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                    getCurrentFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
            if (TextUtils.isEmpty(keyword)) {
                showToast("搜索内容不能为空");
            } else {
                page = 1;
                scrollY = 0;
                sequenceName = "hot";
                storeSearchRecyclerView.scrollToPosition(0);
                storeSearchRefresh.setNoMoreData(false);
                storeSearchRefresh.closeHeaderOrFooter();
                searchGoods();
            }
            return true;
        }
        return false;
    }


    private void setSequence(String sort) {
        if (sequenceName.equals(sort)) return;
        sequenceName = sort;
        storeSequenceSale.setTextColor(0xFF141922);
        storeSequenceCommission.setTextColor(0xFF141922);
        storeSequenceNew.setTextColor(0xFF141922);
        storeSequencePrice.setTextColor(0xFF141922);
        storeSequencePriceicon.setImageResource(R.mipmap.paixu_icon);
        switch (sequenceName) {
            case "hot":
                storeSequenceSale.setTextColor(0xFFF23051);
                break;
            case "commission":
                storeSequenceCommission.setTextColor(0xFFF23051);
                break;
            case "new":
                storeSequenceNew.setTextColor(0xFFF23051);
                break;
            case "price_asc":
                storeSequencePrice.setTextColor(0xFFF23051);
                storeSequencePriceicon.setImageResource(R.mipmap.paixu_top_icon);
                break;
            case "price_desc":
                storeSequencePrice.setTextColor(0xFFF23051);
                storeSequencePriceicon.setImageResource(R.mipmap.paixu_down_icon);
                break;
            default:
        }
//        storeSearchRecyclerView.scrollToPosition(0);
//        recyclerAdapter.addData(new ArrayList<>(),true);
        page = 1;
        scrollY = 0;
        storeSearchRefresh.setNoMoreData(false);
        storeSearchRefresh.closeHeaderOrFooter();
        ivBackTop.setVisibility(View.GONE);
        searchGoods();
    }

    private void searchGoods() {
        mPresenter.searchGoodList(keyword, page + "", "20", sequenceName, "",
                "", null, null, null, storeId, tag);
    }

    @Override
    public void showSearchGood(SearchProductsBean dataBean) {
        if (dataBean == null) return;
        if (page == 1) {
            if (dataBean.getProducts() != null && dataBean.getProducts().size()>0) {
                emptyRoot.setVisibility(View.GONE);
                storeSearchSequencelayout.setVisibility(View.VISIBLE);
                recyclerAdapter.addData(dataBean.getProducts(), true);
            }else {
                emptyRoot.setVisibility(View.VISIBLE);
                storeSearchSequencelayout.setVisibility(View.GONE);
                recyclerAdapter.addData(new ArrayList<>(), true);
            }
            if (dataBean.getProducts().size()<2&&isStaggered){
                delegateAdapter.setAdapters(adapters);
            }
        } else {
            recyclerAdapter.addData(dataBean.getProducts(), false);
        }

        if (!dataBean.isHas_more() || dataBean.getProducts() == null ||dataBean.getProducts().size()<1) {
            storeSearchRefresh.finishLoadMoreWithNoMoreData();
        }else {
            storeSearchRefresh.finishRefresh();
            storeSearchRefresh.finishLoadMore();
        }
        page++;
    }

    @Override
    public void loadFailed() {
        storeSearchRefresh.finishRefresh(false);
        storeSearchRefresh.finishLoadMore(false);
    }
}
